package com.autumn.mybatis.context;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import com.autumn.mybatis.mapper.AutumnMybatisClassPathMapperScanner;
import com.autumn.mybatis.provider.IDbProvider;
import com.autumn.spring.boot.bean.AbstractImportBeanDefinitionRegister;
import com.autumn.spring.boot.bean.BeanDefinitionRegisterManager;
import com.autumn.util.tuple.TupleTwo;

/**
 * 动态数据源注册
 * 
 * @author 老码农
 *         <p>
 *         Description
 *         </p>
 * @date 2017-12-29 20:53:35
 */
public class AutumnMybatisDynamicDataSourceDefinitionRegister extends AbstractImportBeanDefinitionRegister
		implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {

	/**
	 * 
	 */
	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

		DefinitionRegistrarInfo regInfo = DefinitionRegistrarUtils
				.dynamicDataSourceMapperScannerRegistrarInfos(this.getEnvironment(), importingClassMetadata);

		AutumnMybatisClassPathMapperScanner scanner = new AutumnMybatisClassPathMapperScanner(registry);
		if (this.getResourceLoader() != null) {
			scanner.setResourceLoader(this.getResourceLoader());
		}

		BeanDefinitionRegisterManager regManager = new BeanDefinitionRegisterManager(this.getEnvironment(),
				this.getResourceLoader(), registry);

		TupleTwo<String, Class<? extends IDbProvider>> provider = DefinitionRegistrarUtils
				.registerDbProvider(regManager, regInfo);

		DefinitionRegistrarUtils.registerDynamicDataSource(regManager, regInfo, provider);
		scanner.setMapperRegisterBeanName(regInfo.getMapperRegisterBeanName());
		scanner.setSqlSessionFactoryBeanName(regInfo.getSqlSessionFactoryBeanName());
		scanner.setSqlSessionTemplateBeanName(regInfo.getSqlSessionTemplateBeanName());

		scanner.registerFilters();
		scanner.doScan(regInfo.getMapperInterfacePackages());

	}

}
